package com.xl.basic.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xl.basic.utils.JacksonUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.experimental.Accessors;

import java.util.Objects;

/**
 * 统一的数据返回
 * @param <T>
 */
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {

    @NonNull
    @JsonProperty("Code")
    private Integer code;

    @NonNull
    @JsonProperty("Message")
    private String message;

    @JsonProperty("Result")
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private T result;

    @JsonProperty("Total")
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private Long total;

    public Result(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.result = data;
    }

    @JsonIgnore
    public <S> Result<S> create() {
        return new Result<>(code, message);
    }

    @JsonIgnore
    public boolean isSuc() {
        return Objects.equals(code, ResultEnums.Success.getCode());
    }

    @JsonIgnore
    public boolean isErr() {
        return !isSuc();
    }

    @Override
    public String toString() {
        try {
            ObjectMapper objectMapper = JacksonUtils.objectMapper();
            return objectMapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
